import React, { useEffect, useState, useMemo } from 'react';
import { Form, Select, Button, Typography, Flex, Input, Image, Upload, message, Dropdown, Popover, Pagination, Tag } from 'antd';
import { SearchOutlined, CheckCircleFilled, CameraOutlined, DeleteOutlined, EyeOutlined, DownOutlined, DownloadOutlined } from '@ant-design/icons';
import { useTranslation } from 'react-i18next';
import { useNavigate, useLocation } from 'react-router-dom';
import _, { method } from 'lodash'
import { download, transformArray } from '../../../../utils/commonUtil';

import ZoomButton from '../../../Components/ZoomButton';
import ChooseImageModal from '../ChooseImageModal'
import './index.scss'

const { Title } = Typography;
const PageSemIrSearch = ({ pageTitle, page, methodList, apiFilter, apiList, defaultMethod }) => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const location = useLocation();
  const queryParams = location?.state || {};
  const { chooseImageDefault = {} } = queryParams
  console.log("🚀 ~ SynTouchRequestDetails ~ queryParams:", queryParams)
  const [file, setFile] = useState()
  const [form] = Form.useForm();
  const [imgSelected, setImgSelected] = useState([])

  const [zoom, setZoom] = useState(0)
  const imgWidth = useMemo(() => 120 + (zoom * 50), [zoom])
  const [visible, setVisible] = useState(false);
  // 下拉框数据
  const [buList, setBuList] = useState([]);
  const [projectList, setProject] = useState([]);
  const [productList, setProduct] = useState([]);
  const [requesterList, setRequester] = useState([]);
  const [tagList, setTag] = useState([]);
  // 分页相关
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(20);
  const [totalPage, setTotalPage] = useState(0);
  // list 页面数据
  const [dataList, setDataList] = useState();

  const [selectedTags, setSelectedTags] = useState([]);

  const [chooseImageModalVisable, setChooseImageModalVisable] = useState(false)
  const [isUploadImage, setIsUploadImage] = useState()
  const [chooseImage, setChooseImage] = useState(chooseImageDefault)


  useEffect(() => {
    // 正式数据
    queryList();
    // 调用下拉框api
    queryFilter()
  }, [])

  // 调用下拉框api
  const queryFilter = async () => {
    const res = await apiFilter()
    if (res?.data?.code === 200) {
      setBuList(transformArray(res?.data?.data?.buType));
      setProject(transformArray(res?.data?.data?.projectName));
      setProduct(transformArray(res?.data?.data?.productName));
      setRequester(transformArray(res?.data?.data?.requester));
      setTag(res?.data?.data?.tag);
    }
  };
  const getQueryParams = () => {
    const formData = form.getFieldsValue();
    const params = {
      buTypes: formData?.buTypes,
      projectNames: formData?.projectNames,
      productNames: formData?.productNames,
      requesters: formData?.requesters,
      tags: selectedTags
    };
    return params;
  };
  // 获取页面list数据
  const queryList = async (pagination, size) => {
    const params = {
      ...getQueryParams(),
      page: pagination || currentPage,
      limit: size || pageSize
    };
    const res = await apiList(params)
    if (res?.data?.code === 200) {
      const list = res?.data?.data?.items
      // if (chooseImage.imageAttachment && chooseImage.imageAttachment.length > 0) {
      //   list.unshift({
      //     fileName: chooseImage.imageAttachment[0].name,
      //     filePath: chooseImage.imageAttachment[0].attachmentUrl
      //   })
      // }
      // console.log("chooseImage.imageAttachment", list, chooseImage)

      setDataList(list);
      setTotalPage(res?.data?.data?.total);
    }

  };
  const serach = () => {
    setCurrentPage(1);
    queryList(1);
    setImgSelected([])
  };



  const onChangePreview = (value) => {
    setVisible(value === false ? false : value)
  }

  const onPreview = (e, index, isChoose) => {
    if (isChoose) {
      index = 0
    } else if (chooseImage.imageAttachment && chooseImage.imageAttachment.length > 0) {
      index += 1
    }
    e.stopPropagation()
    setVisible(index);
  }

  const onChange = ({ file: newFile }) => {
    if (newFile.status === 'error') {
      // message.error(newFile.status);
      setFile(newFile);
    } else if (newFile.status === 'done') {
      setFile(newFile);
    }
  };

  const onSelect = (data, i) => {
    //如果是点击拿来对比的图片直接return
    // if (i === 0 && chooseImage.imageAttachment && chooseImage.imageAttachment.length > 0) {
    //   return
    // }
    const index = imgSelected.findIndex(val => val.filePath === data.filePath)
    if (index >= 0) {
      imgSelected.splice(index, 1)
    } else {
      imgSelected.push(data)
    }
    setImgSelected([...imgSelected])

  }


  const content = (data) => {
    if (!data) {
      return false
    }
    return (
      <>
        {Object.keys(data || {}).map((key, i) => (
          <div key={i}>{key}: {data[key]}</div>
        ))}
      </>
    )
  }

  const toComparison = () => {
    navigate('/search/SEMComparison', {
      state: {
        page
      }
    })
  }

  const handleUploadImage = (isTrue) => {
    setIsUploadImage(isTrue)
    setChooseImageModalVisable(true)
  }

  const onConfirmModal = (data) => {
    if (isUploadImage) {

    } else {
      data.imageAttachment = [{
        attachmentUrl: imgSelected[0].filePath,
        name: imgSelected[0].fileName,
      }]
    }
    console.log("🚀 ~ onConfirmModal ~ data:", data)

    setChooseImage(data)
    setCurrentPage(1);
    queryList(1);
    setImgSelected([])
  }

  const handleChange = (tag, checked) => {
    const nextSelectedTags = checked
      ? [...selectedTags, tag]
      : selectedTags.filter((t) => t !== tag);
    setSelectedTags(nextSelectedTags);
  };

  const imgItemRender = ({ d, i, isChoose }) => {
    const imgWidth = 120 + (zoom * 50)
    return (
      <div
        className={[
          imgSelected.some(val => val.filePath === d.filePath) && !isChoose ? 'item selected' : 'item',
          isChoose ? 'choosed' : ''
        ].join(' ')}
        onClick={() => isChoose ? false : onSelect(d, i)}
        style={{ width: imgWidth }}
        key={`${i}_${d.filePath}`}>
        <Popover placement="left" trigger="hover" content={content(d.fieldValueMap)} >
          <div className='imgBox' style={{ width: imgWidth, height: imgWidth }}>
            <Image
              src="https://gw.alipayobjects.com/zos/antfincdn/LlvErxo8H9/photo-1503185912284-5271ff81b9a8.webp"
              className="img" />

            <div className='mask'>
              <div onClick={(e) => onPreview(e, i, isChoose)}>
                <EyeOutlined className='iconPreview' />
                <span>{t('common.preview')}</span>
              </div>
            </div>
          </div>
        </Popover>


        <CheckCircleFilled className='iconCheck' />

        <div className='name'>{d.fileName}</div>

      </div>
    )
  }

  return (
    <div className='wrapSEM'>
      <div className='page-title-wrap'>
        <Flex align='center' justify='space-between'>
          <Title className='fontStyleH2' level={2} >{pageTitle}</Title>
        </Flex>
      </div>
      <div className='page-content-wrap'>
        <Flex>
          <Form form={form} className='filter-wrap form' labelCol={{ span: 24 }} wrapperCol={{ span: 24 }}>

            <div className='title'>{t('common.filter')}</div>
            <Form.Item
              name="keywords"
              label={t('common.keywords')}
              className='filterItem'>
              <Input placeholder={t('common.PleaseInput')} />
            </Form.Item>
            <Form.Item
              name="buTypes"
              label={t('common.bu')}
              className='filterItem'>
              <Select mode="multiple" allowClear options={buList} placeholder={t('common.pleaseSelect')} />
            </Form.Item>
            <Form.Item
              name="projectNames"
              label={t('search.projectName')}
              className='filterItem'>
              <Select mode="multiple" allowClear options={projectList} placeholder={t('common.pleaseSelect')} />
            </Form.Item>
            <Form.Item
              name="productNames"
              label={t('search.productName')}
              className='filterItem'>
              <Select mode="multiple" allowClear options={productList} placeholder={t('common.pleaseSelect')} />
            </Form.Item>
            <Form.Item
              name="requesterNames"
              label={t('search.requesterName')}
              className='filterItem'>
              <Select mode="multiple" allowClear options={requesterList} placeholder={t('common.pleaseSelect')} />
            </Form.Item>
            <Form.Item
              name="tags"
              label={t('common.tag')}
              className='filterItem'>
              <div className='tagBox'>
                {tagList.map((tag) => (
                  <Tag.CheckableTag
                    key={tag}
                    checked={selectedTags.includes(tag)}
                    onChange={(checked) => handleChange(tag, checked)}
                  >
                    {tag}
                  </Tag.CheckableTag>
                ))}
              </div>
            </Form.Item>
            <Form.Item noStyle >
              <Button
                className='search-btn'
                type="primary"
                icon={<SearchOutlined style={{ fontSize: 13 }} />}
                onClick={serach}
              />
            </Form.Item>

          </Form>
          <div className='content'>
            <Flex justify='space-between'>
              <Flex gap={12}>
                <ZoomButton
                  onChange={setZoom}
                  value={zoom} />
                <Button
                  className='search-btn'
                  // onClick={() => onChangeZoom(false)}
                  disabled={imgSelected.length < 1}
                  icon={<DownloadOutlined style={{ fontSize: 20 }} />}
                />
              </Flex>
              <Flex gap={12}>
                <Button type="primary" onClick={() => handleUploadImage(true)} ghost>{t('search.searchImage')}</Button>
                <Popover placement="top" trigger="hover" content={imgSelected.length !== 1 ? t("search.PleaseSelectImage") : false} >
                  <Button
                    type="primary"
                    onClick={() => handleUploadImage(false)}
                    disabled={imgSelected.length !== 1}
                    ghost>{t('search.chooseImage')}</Button>
                </Popover>

                <Popover placement="top" trigger="hover" content={imgSelected.length < 1 ? t("search.PleaseSelectImage") : false} >
                  <Button
                    className='search-btn'
                    type="primary"
                    disabled={imgSelected.length < 1}
                    onClick={toComparison}
                  >{t('search.comparison')}</Button>
                </Popover>

              </Flex>


            </Flex>
            {chooseImage?.method && <div className='methodName'>{chooseImage.method}</div>}

            <Flex className='list' wrap='wrap' gap={28}>
              <Image.PreviewGroup
                preview={visible !== false ? {
                  visible: true,
                  onVisibleChange: (value) => {
                    onChangePreview(value);
                  },
                  onChange: (current, prev) => {
                    onChangePreview(current)
                    console.log(`current index: ${current}, prev index: ${prev}`)
                  },
                  current: visible
                } : false}>

                {
                  chooseImage?.imageAttachment?.length > 0 && imgItemRender({
                    d: {
                      filePath: chooseImage.imageAttachment[0].attachmentUrl,
                      fileName: chooseImage.imageAttachment[0].name
                    },
                    i: 99999,
                    isChoose: true
                  })
                }

                {
                  (dataList || []).map((d, i) => imgItemRender({ d, i }))
                }

              </Image.PreviewGroup>
            </Flex>
            {
              totalPage > 0 && (
                <Flex justify='flex-end'>
                  <Pagination
                    size="small"
                    className='pagination'
                    total={totalPage}
                    showTotal={(total) => `Total ${total} items`}
                    current={currentPage}
                    pageSize={pageSize}
                    onChange={(_crrentPage, _pageSize) => {
                      setCurrentPage(_crrentPage);
                      setPageSize(_pageSize);
                      queryList(_crrentPage, _pageSize);
                    }}
                    pageSizeOptions={[10, 20, 50]}
                    showSizeChanger={true}
                  />
                </Flex>
              )
            }


          </div>
        </Flex>
      </div>
      <ChooseImageModal
        chooseImageModalVisable={chooseImageModalVisable}
        setChooseImageModalVisable={setChooseImageModalVisable}
        isUploadImage={isUploadImage}
        methodList={methodList}
        defaultValue={chooseImageDefault}
        onConfirm={onConfirmModal} />
    </div>
  )
}

export default PageSemIrSearch;
